package com.yjz.jvm.introspector;

import org.junit.Test;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class IntrospectorTest {

  /**
   * 对象转map，内省的写法
   *
   * @throws IntrospectionException
   * @throws InvocationTargetException
   * @throws IllegalAccessException
   */
  @Test
  public void objectToMapByIntrospector() throws IntrospectionException, InvocationTargetException, IllegalAccessException {
    Student st = new Student();
    st.setAddress("江苏无锡");
    st.setAge("26");
    st.setName("袁金忠");
    BeanInfo beanInfo = Introspector.getBeanInfo(st.getClass());
    PropertyDescriptor[] propertyArr = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : propertyArr) {
      String key = propertyDescriptor.getName();
      if (key.compareToIgnoreCase("class") != 0) {
        Method getter = propertyDescriptor.getReadMethod();
        Object value = getter.invoke(st);
        System.out.println("属性：" + key + "对应的值是:" + value);
      }
      /**
       单元测试输出结果：
       属性：address对应的值是:江苏无锡
       属性：age对应的值是:26
       属性：class对应的值是:class com.yjz.jvm.introspector.Student
       属性：name对应的值是:袁金忠
       */

    }
  }

  /**
   * 对象转map ，反射写法
   */
  @Test
  public void ObjectToMapByReflect() throws IllegalAccessException {
    Student st = new Student();
    st.setAddress("江苏无锡");
    st.setAge("26");
    st.setName("袁金忠");

    Field[] fieldArr = st.getClass().getDeclaredFields();
    for (Field field : fieldArr) {
      field.setAccessible(true);
      String key = field.getName();
      Object value = field.get(st);
      System.out.println("属性：" + key + "对应的值是:" + value);
    }

  }


}
